//
//  ThreadedHelper.m
//  WSPluginSwitcher
//
//  Created by Marc Bauer on 19.01.09.
//  Copyright 2009 nesiumdotcom. All rights reserved.
//

#import "ThreadedHelper.h"


@implementation ThreadedHelper

#pragma mark -
#pragma mark Initialization & Deallocation

- (id)init
{
	if (self = [super init])
	{
		m_worker = [[Worker alloc] init];
		m_connection = nil;
	}
	return self;
}

- (void)dealloc
{
	[m_worker release];
	[m_connection release];
	[super dealloc];
}



#pragma mark -
#pragma mark Public methods

- (void)run
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	m_runLoop = [NSRunLoop currentRunLoop];
	m_currentThread = [NSThread currentThread];
	NSMachPort *sendPort = (NSMachPort *)[[NSMachBootstrapServer sharedInstance] 
		portForName:kConnectionName];
	
	Worker *worker = [[Worker alloc] init];
	m_connection = [[NSConnection alloc] 
		initWithReceivePort:(NSPort *)[[sendPort class] port] 
		sendPort:sendPort];
	[[m_connection rootProxy] setProtocolForProxy:@protocol(WorkerDelegate)];
	worker.delegate = (NSObject <WorkerDelegate> *)[m_connection rootProxy];
	[worker awake];

	CFRunLoopRun();
	
	[m_connection invalidate];
	[pool drain];
	[pool release];
}

- (void)terminate
{
	CFRunLoopStop([m_runLoop getCFRunLoop]);
}

@end